package com.cos.hospital.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * @Description: 对外暴露Scroll的状态
 * @apiNote 尼玛，这玩意真特么坑
 * @Author: Kosmos
 * @Date: 2018年09月28日 0:17
 * @Email: KosmoSakura@foxmail.com
 */
public class KScrollView extends ScrollView {
    private ScrollListener listener;
    private final int what_code = 9010;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == what_code) {
                if (listener != null) {
                    listener.onStateChanged(msg.arg1 == MotionEvent.ACTION_MOVE);
                }
            }
            return false;
        }
    });

    public void setScrollStateListener(ScrollListener listener) {
        this.listener = listener;
    }

    public interface ScrollListener {
        void onStateChanged(boolean isMoving);
    }


    public KScrollView(Context context) {
        super(context);
    }

    public KScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public KScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 测试结果：
     * 点击：按下-抬起(不足一页时只有：按下
     * 移动：按下-移动
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (listener != null) {
            sendMsgDely(ev.getAction());
//            switch (ev.getAction()) {
//                case MotionEvent.ACTION_DOWN:
//                    LogInterceptor.d("Sakura", "1-----按下");
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    LogInterceptor.d("Sakura", "2-----移动");
//                    break;
//                case MotionEvent.ACTION_UP:
//                    LogInterceptor.d("Sakura", "3-----抬起");
//                    break;
//                default:
//                    LogInterceptor.d("Sakura", "4-----ev.getAction()");
//                    break;
//            }
        }

        return super.onInterceptTouchEvent(ev);
    }

    private void sendMsgDely(int state) {
        if (handler.hasMessages(what_code)) {
            handler.removeMessages(what_code);
        }
        Message msg = handler.obtainMessage();
        msg.what = what_code;
        msg.arg1 = state;
        handler.sendMessageDelayed(msg, 200);//延迟200毫秒
    }
}
